package com.ruoyi.project.wxapi.controller;

import java.util.List;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.project.wxapi.config.WxMaConfiguration;
import com.ruoyi.project.wxapi.controller.util.JWTUtil;
import com.ruoyi.project.wxapi.model.bean.Nurse;
import com.ruoyi.project.wxapi.model.dto.Result;
import com.ruoyi.project.wxapi.model.qo.BaseParamQO;
import com.ruoyi.project.wxapi.model.qo.WxInfoQO;
import com.ruoyi.project.wxapi.model.service.INurseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 医生、护士、照护师Controller
 * 
 * @author finley
 * @date 2021-04-14
 */
@Controller
@RequestMapping("/wxapi/nurse")
@Slf4j
public class NurseController extends BaseController
{
    private String prefix = "wxapi/nurse";

    @Autowired
    private INurseService nurseService;

    /**
     * 照护师微信登录
     *
     * @param wxInfoQO
     * @return
     */
    @RequestMapping(value = "/loginByWx",method = RequestMethod.POST)
    public Result loginByWx(@RequestBody WxInfoQO wxInfoQO)
    {
        final WxMaService wxService = WxMaConfiguration.getMaService(wxInfoQO.getAppid());

        try{
            //根据openid查询用户信息
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(wxInfoQO.getCode());
            Nurse nurse = nurseService.selectNurseByOpenid(session.getOpenid());
            //如果用户不存在，则注册
            if(nurse == null)
            {
                nurse.setOpenid(session.getOpenid());
                nurse.setAvatar(wxInfoQO.getAvatarUrl());
                nurse.setGender(wxInfoQO.getGender());
                nurse.setName(wxInfoQO.getNickName());
                nurse.setPhone(wxInfoQO.getPhoneNumber());
                nurse.setLiveProvince(wxInfoQO.getProvince());
                nurse.setLiveCity(wxInfoQO.getCity());
                nurseService.insertNurse(nurse);
            }

            String jwtToken = JWTUtil.generateJWT(nurse.getId());
            JSONObject data = new JSONObject();
            data.put("userid", nurse.getId());
            data.put("token", jwtToken);
            data.put("status",nurse.getStatus());
            data.put("checkMessage",nurse.getCheckMessage());
            return Result.success(data);
        }catch(Exception e)
        {
            log.error(e.getMessage(),e);
            return Result.error(HttpStatus.HTTP_BAD_METHOD,"系统异常");
        }
    }

    /**
     * 申请审核
     *
     * @param nurse
     * @return
     */
    @RequestMapping(value = "applyCheck",method = RequestMethod.POST)
    public Result applyCheck(Nurse nurse,@RequestHeader("token") String token)
    {
        Integer userId = JWTUtil.parseJWT(token);
        return Result.success();
    }

    @RequiresPermissions("wxapi:nurse:view")
    @GetMapping()
    public String nurse()
    {
        return prefix + "/nurse";
    }

    /**
     * 查询医生、护士、照护师列表
     */
    @RequiresPermissions("wxapi:nurse:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Nurse nurse)
    {
        startPage();
        List<Nurse> list = nurseService.selectNurseList(nurse);
        return getDataTable(list);
    }

    /**
     * 导出医生、护士、照护师列表
     */
    @RequiresPermissions("wxapi:nurse:export")
    @Log(title = "医生、护士、照护师", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Nurse nurse)
    {
        List<Nurse> list = nurseService.selectNurseList(nurse);
        ExcelUtil<Nurse> util = new ExcelUtil<Nurse>(Nurse.class);
        return util.exportExcel(list, "nurse");
    }

    /**
     * 新增医生、护士、照护师
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存医生、护士、照护师
     */
    @RequiresPermissions("wxapi:nurse:add")
    @Log(title = "医生、护士、照护师", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Nurse nurse)
    {
        return toAjax(nurseService.insertNurse(nurse));
    }

    /**
     * 修改医生、护士、照护师
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        Nurse nurse = nurseService.selectNurseById(id);
        mmap.put("nurse", nurse);
        return prefix + "/edit";
    }

    /**
     * 修改保存医生、护士、照护师
     */
    @Log(title = "医生、护士、照护师", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestBody Nurse nurse, @RequestHeader String token)
    {
        Integer userId = JWTUtil.parseJWT(token);
        nurse.setId(userId);
        return toAjax(nurseService.updateNurse(nurse));
    }

    /**
     * 删除医生、护士、照护师
     */
    @RequiresPermissions("wxapi:nurse:remove")
    @Log(title = "医生、护士、照护师", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(nurseService.deleteNurseByIds(ids));
    }

    @GetMapping( "/query")
    @ResponseBody
    public AjaxResult query(@RequestHeader String token)
    {
        Integer userId = JWTUtil.parseJWT(token);
        Nurse nurse = nurseService.selectNurseById(userId);

        return AjaxResult.success(nurse);
    }
}
